package org.base.admin.modules.sys.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.base.admin.modules.sys.service.SysUserRoleService;
import org.base.admin.modules.sys.service.SysUserService;
import org.base.dao.modules.base.BaseServiceImpl;
import org.base.dao.modules.sys.mapper.SysMenuDao;
import org.base.dao.modules.sys.mapper.SysUserDao;
import org.base.dao.modules.sys.model.SysUserDO;
import org.base.dao.modules.sys.model.SysUserRoleMapDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class SysUserServiceImpl extends BaseServiceImpl<SysUserDO, SysUserDao> implements SysUserService {
	
	@Autowired
	private SysMenuDao sysMenuDao;
	
	@Autowired
	private SysUserRoleService sysUserRoleService;
	
	@Override
	public SysUserDO findByUsername(String username) {
		SysUserDO user = baseDao.findByUsername(username);
		user.setAuthorities(this.authorities(user));
		return user;
	}

	@Override
	public Set<String> authorities(SysUserDO user) {
		if(user.isAdmin()) {
			return sysMenuDao.findAuthorities();
		}return null;
	}
	
	@Transactional
	@Override
	public boolean save(SysUserDO entity) {
		super.save(entity);
		if(CollectionUtils.isEmpty(entity.getRoleIds()))return true;
		List<SysUserRoleMapDO> userRoles = new ArrayList<>();
		entity.getRoleIds().forEach(roleId->{
			SysUserRoleMapDO userRole = new SysUserRoleMapDO(entity.getId(), roleId);
			userRoles.add(userRole);
		});
		return sysUserRoleService.saveBatch(userRoles);
	}

}
